package com.wlhse.service.impl;

import com.github.pagehelper.PageHelper;
import com.wlhse.dao.StudyCaseDao;
import com.wlhse.entity.StudyCasePojo;
import com.wlhse.exception.WLHSException;
import com.wlhse.service.StudyCaseService;
import com.wlhse.util.state_code.CodeDict;
import com.wlhse.util.state_code.NR;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class StudyCaseServiceImpl implements StudyCaseService {

    @Resource
    private StudyCaseDao studyCaseDao;

    @Resource
    private StudyCasePojo studyCasePojo;

    @Value("${RESOURCES_URL}")
    private String url;


    @Override
    @Transactional
    public String addStudyCase(StudyCasePojo studyCasePojo) {
        if (studyCaseDao.addStudyCase(studyCasePojo) <= 0)
            throw new WLHSException("新增失败");
        return NR.r();
    }

    @Override
    @Transactional
    public String deleteStudyCase(Integer id) {
        if (studyCaseDao.deleteStudyCase(id) <= 0)
            throw new WLHSException("删除失败");
        return NR.r();
    }

    @Override
    @Transactional
    public String updateStudyCase(StudyCasePojo studyCasePojo) {
        if (studyCaseDao.updateStudyCase(studyCasePojo) <= 0)
            throw new WLHSException("更新失败");
        return NR.r();
    }

    @Override
    public String queryStudyCases(StudyCasePojo studyCasePojo) {
        studyCasePojo.setUrl(url);
        if (StringUtils.isNotBlank(studyCasePojo.getStartDate()) && StringUtils.isBlank(studyCasePojo.getEndDate())) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            studyCasePojo.setEndDate(df.format(new Date()));// new Date()为获取当前系统时间
        }
        if (studyCasePojo.getType().equals("all"))
            return NR.r(studyCaseDao.queryStudyCases(studyCasePojo));
        int total = studyCaseDao.queryStudyCasesCount(studyCasePojo);
        PageHelper.startPage(studyCasePojo.getPageIdx(), studyCasePojo.getPageSize());
        List<StudyCasePojo> list = studyCaseDao.queryStudyCases(studyCasePojo);
        return NR.r(list, total, studyCasePojo.getPageIdx());
    }

    public String queryStudyCasesById(int id) {
        return NR.r(studyCaseDao.queryStudyCasesById(id, url));
    }
}
